<template>
  <el-dialog
    :title="!dataForm.billCode ? '新增' : '修改'" :close-on-click-modal="false"
    :visible.sync="visible" width="90%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="120px">
      <el-form-item label="项目编号：" prop="projectNo">
        <strong>{{dataForm.projectNo}}</strong>
      </el-form-item>
      <el-form-item label="项目名称：" prop="projectNo">
        <strong>{{dataForm.projectName}}</strong>
      </el-form-item>
      <el-form-item prop="projectBill" label="成果交接单：">
        <div class="bill_line">
          <span class="title_span"></span>
          <el-button icon="el-icon-plus" type="primary" size="small" @click="addAchItemHandle">添加成果项</el-button>
        </div>
        <el-table border :data="dataForm.achList">
          <el-table-column prop="seqNum" header-align="center" align="center" label="序号" width="80"></el-table-column>
          <el-table-column prop="billName" header-align="center" align="center" label="成果名称">
            <template slot-scope="scope">
              <el-autocomplete v-model="scope.row.billName" :fetch-suggestions="queryNameSearch" @select="((item)=>{handleNameSelect(item, scope.row.seqNum)})" required="true" style="width: 100%">
                <template slot-scope="{ item }">
                  <div class="name">{{ item.nameItem }}</div>
                </template>
              </el-autocomplete>
            </template>
          </el-table-column>
          <el-table-column prop="billNo" header-align="center" align="center" label="成果编号" width="180">
            <template slot-scope="scope">
              <el-input  v-model="scope.row.billNo"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="spec" header-align="center" align="center" label="规格" width="180">
            <template slot-scope="scope">
              <el-autocomplete v-model="scope.row.spec" :fetch-suggestions="querySpecSearch" @select="((item)=>{handleSpecSelect(item, scope.row.seqNum)})">
                <template slot-scope="{ item }">
                  <div class="name">{{ item.nameItem }}</div>
                </template>
              </el-autocomplete>
            </template>
          </el-table-column>
          <el-table-column prop="style" header-align="center" align="center" label="样式" width="150">
            <template slot-scope="scope">
              <el-autocomplete v-model="scope.row.style" :fetch-suggestions="queryStyleSearch" @select="((item)=>{handleStyleSelect(item, scope.row.seqNum)})" required="true" style="width: 100%">
                <template slot-scope="{ item }">
                  <div class="name">{{ item.nameItem }}</div>
                </template>
              </el-autocomplete>
            </template>
          </el-table-column>
          <el-table-column prop="num" header-align="center" align="center" label="数量(份)" width="100">
            <template slot-scope="scope">
              <el-input  v-model="scope.row.num" type="number"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="remark" header-align="center" align="center" label="备注" width="100">
            <template slot-scope="scope">
              <el-autocomplete v-model="scope.row.remark" :fetch-suggestions="queryRemarkSearch" @select="((item)=>{handleRemarkSelect(item, scope.row.seqNum)})">
                <template slot-scope="{ item }">
                  <div class="name">{{ item.nameItem }}</div>
                </template>
              </el-autocomplete>
            </template>
          </el-table-column>
          <el-table-column  header-align="center" align="center" label="操作" width="80">
            <template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteBillHandle(scope.row.seqNum)" v-if="scope.row.seqNum !== dataForm.achList.length"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import moment from 'moment'
  import {stringIsNull, treeDataTranslate, getUUID} from '@/utils'
  import {getBillRemarkItem, getBillSpecItem, getBillNameItem,getBillStyleItem} from '@/utils/selectedItem'

  export default {
    data () {
      return {
        visible: false,
        dataForm: {
          id: 0,
          projectNo: '',
          projectName: '',
          billCode: '',
          achList: []
        },
        // 默认成果编号
        billNodef: '',
        dataRule: {
          projectNo: [
            { required: true, message: '项目编号不能为空', trigger: 'blur' }
          ],
          billCode: [
            { required: true, message: '清单编号不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (item) {
        this.dataForm.billCode = item.billCode || 0
        this.dataForm.projectNo = item.projectNo || 0
        this.dataForm.projectName = item.projectName
        this.dataForm.achList = []
        this.visible = true
        this.$nextTick(() => {
          // 修改的清单
          if (this.dataForm.billCode && this.dataForm.projectNo) {
            this.getExpachList().then(list => {
              this.dataForm.achList = list
            })
          } else {
            // 新增的清单
            this.getLastExpachList().then(dat => {
              let billNodef = this.dataForm.projectNo + (dat.maxCode > 1 ? ('-' + String.fromCharCode(dat.maxCode + 95).toUpperCase()) : '')
              console.log(billNodef)
              if (dat.list.length > 0) {
                dat.list.forEach( (item,index) => {
                  item.billCode = dat.maxCode
                  item.billNo = billNodef
                  item.id = ''
                })
                this.dataForm.achList = dat.list
              } else {
                let bList = []
                item.billList.forEach((billItem,index) => {
                  let bitem = {
                    seqNum: index + 1,
                    billName: billItem.billName,
                    billNo: billNodef,
                    spec: billItem.spec,
                    num: billItem.num
                  }
                  bList.push(bitem)
                })
                let lastItem = {
                  billName: '以上成果电子版',
                  seqNum: item.billList.length + 1
                }
                bList.push(lastItem)
                this.dataForm.achList = bList
              }
            })
          }
        })
      },
      // 获取成果清单
      getExpachList () {
        return new Promise((resolve, reject) => {
          this.$http({
            url: this.$http.adornUrl(`/project/expach/list`),
            method: 'get',
            params: this.$http.adornParams({
              projectNo: this.dataForm.projectNo,
              billCode: this.dataForm.billCode
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              resolve(data.list)
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 获取最后一次成果清单
      getLastExpachList () {
        return new Promise((resolve, reject) => {
          this.$http({
            url: this.$http.adornUrl(`/project/expach/lastList`),
            method: 'get',
            params: this.$http.adornParams({
              projectNo: this.dataForm.projectNo
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              resolve(data)
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 项目清单名
      queryNameSearch (queryString, cb) {
        var list = getBillNameItem()
        var results = queryString ? list.filter(this.createFilter(queryString)) : list
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      // 样式
      queryStyleSearch (queryString, cb) {
        var list = getBillStyleItem()
        var results = queryString ? list.filter(this.createFilter(queryString)) : list
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      // 规格选项
      querySpecSearch (queryString, cb) {
        var list = getBillSpecItem()
        var results = queryString ? list.filter(this.createFilter(queryString)) : list
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      // 备注选项
      queryRemarkSearch (queryString, cb) {
        var list = getBillRemarkItem()
        var results = queryString ? list.filter(this.createFilter(queryString)) : list
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      createFilter (queryString) {
        return (restaurant) => {
          return (restaurant.nameItem.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
        }
      },
      handleNameSelect (item,sNum) {
        this.dataForm.achList.find(dat => dat.seqNum === sNum).billName = item.nameItem
      },
      handleStyleSelect (item,sNum) {
        this.dataForm.achList.find(dat => dat.seqNum === sNum).style = item.nameItem
      },
      handleSpecSelect (item,sNum) {
        this.dataForm.achList.find(dat => dat.seqNum === sNum).spec = item.nameItem
      },
      handleRemarkSelect (item,sNum) {
        this.dataForm.achList.find(dat => dat.seqNum === sNum).remark = item.nameItem
      },
      // 添加项目清单项
      addAchItemHandle () {
        let billItem = {
          'projectNo': this.dataForm.projectNo,
          'billName': '',
          'billNo': '',
          'style': '',
          'spec': '',
          'num': 0,
          'remark': ''
        }
        this.dataForm.achList.splice(this.dataForm.achList.length - 1, 0, billItem)
        this.dataForm.achList.forEach( (item,index) => {
          item.seqNum = index + 1
          item.billNo = item.seqNum === this.dataForm.achList.length ? '' : this.prefixInteger(index + 1, 3)
        })
      },
      // 删除项目清单项
      deleteBillHandle (id) {
        if (this.dataForm.achList.length <= 1) {
          this.$message.error('该项目成果项无法删除，请仔细填写！')
          return
        }
        let billList = []
        for (let bill of this.dataForm.achList) {
          if (bill.seqNum !== id) {
            billList.push(bill)
          }
        }
        billList.forEach( (item,index) => {
          item.seqNum = index + 1
          item.billNo = item.id === 'z' ? '' : this.prefixInteger(index + 1, 3)
        })
        this.dataForm.achList = billList
      },
      // 数字转字符右边补零
      prefixInteger (num, length) {
        return (Array(length).join('0') + num).slice(-length)
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          this.dataForm.achList.forEach( (item,index) => {
            item.projectNo = this.projectNo
          })
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/project/expach/save`),
              method: 'post',
              data: this.$http.adornData({
                'projectNo': this.dataForm.projectNo,
                'billCode': this.dataForm.billCode,
                'achList': this.dataForm.achList
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500
                })
                this.visible = false
                this.$emit('refreshDataList')
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import "src/assets/scss/_variables.scss";
  .bill_line{
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid $--color-primary;
  }
</style>
